package com.ewanghuiju.app.ui.resale.fragment;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.base.RootFragment;
import com.ewanghuiju.app.base.contract.resale.ResaleOrderListContract;
import com.ewanghuiju.app.model.bean.response.PintuanOrderListResponBean;
import com.ewanghuiju.app.model.bean.response.ResaleOrderListResponBean;
import com.ewanghuiju.app.presenter.resale.ResaleOrderListPresenter;
import com.ewanghuiju.app.ui.my.activity.WalletCenterActivity;
import com.ewanghuiju.app.ui.pintuan.activity.PintuanDetailsActivity;
import com.ewanghuiju.app.ui.pintuan.activity.PintuanOrderDetailsActivity;
import com.ewanghuiju.app.ui.pintuan.activity.PintuanPjActivity;
import com.ewanghuiju.app.ui.resale.adapter.ResaleOrderListAdapter;
import com.ewanghuiju.app.ui.web.MyWebviewActivity;
import com.ewanghuiju.app.util.LoadingDialogUtils;
import com.ewanghuiju.app.util.StartActivityUtil;
import com.ewanghuiju.app.util.StringUtil;
import com.ewanghuiju.app.util.thread.LoadImageDataThread;
import com.luck.picture.lib.PictureMediaScannerConnection;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.tools.SdkVersionUtils;
import com.luck.picture.lib.tools.ToastUtils;
import com.muddzdev.styleabletoast.StyleableToast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

/**
 * @author sj  qq:751943509
 * @class 转售订单列表
 * @time 2020/2/28
 */
public class ResaleOrderListFragment extends RootFragment<ResaleOrderListPresenter> implements ResaleOrderListContract.View {
    @BindView(R.id.view_main)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private int mType;

    private ResaleOrderListAdapter adapter;

    private int currentPage = 1;

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_pintuan_order_list;
    }

    @Override
    protected void initEventAndData() {
        super.initEventAndData();
        initRefreshLayout();
        initRecylerView();
    }

    private void initRecylerView() {
        mType = StringUtil.getOrderTypeBy(getArguments().getInt(Constants.PINTUANORDER_TYPE));
        recyclerView.setNestedScrollingEnabled(false);
        LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(mLinearLayoutManager);
        adapter = new ResaleOrderListAdapter(R.layout.item_pintuan_order_list, mType);
        adapter.setButtonClick(new ResaleOrderListAdapter.OnButtonClick() {
            @Override
            public void onKefu() {
                //客服
                new StartActivityUtil(activity, MyWebviewActivity.class).putExtra("url", Constants.WEBURL_KEFU)
                        .putExtra(Constants.WEBURL_TITLE, Constants.WEBURL_KEFU_TITLE).startActivity(true);
            }

            @Override
            public void onLookwl(String url) {
                if (TextUtils.isEmpty(url)) {
                    StyleableToast.makeText(context, "未查询到信息", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    return;
                }
                new StartActivityUtil(activity, MyWebviewActivity.class).putExtra("url", url)
                        .putExtra(Constants.WEBURL_TITLE, Constants.WEBURL_KUAIDI_TITLE).startActivity(true);
            }

            @Override
            public void onSuresh(int orderId) {
                //确认收货
//                toSureSh(orderId + "");
            }

            @Override
            public void onInviteFriend(String goodsid, String groupid) {
                if (TextUtils.isEmpty(groupid)) {
                    StyleableToast.makeText(activity, "未获取到信息,无法查看", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    return;
                }
                new StartActivityUtil(activity, PintuanDetailsActivity.class)
                        .putExtra(Constants.PINTUAN_GROUP_ID, groupid)
                        .startActivity(true);
            }

            @Override
            public void onLookWallet() {
                //查看钱包
                new StartActivityUtil(context, WalletCenterActivity.class).startActivity(true);
            }

            @Override
            public void onLjpj(PintuanOrderListResponBean bean) {
                //立即评价
                if (bean == null) {
                    StyleableToast.makeText(context, "未获取到商品信息,无法进行评价", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    return;
                }
                new StartActivityUtil(context, PintuanPjActivity.class)
                        .putExtra(Constants.PINTUAN_ID, bean.getId())
                        .putExtra(Constants.PINTUAN_TITLE, bean.getGoods_name())
                        .putExtra(Constants.PINTUAN_IMAGE, bean.getImage())
                        .startActivity(true);
            }
        });
        adapter.setHasStableIds(true);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                PintuanOrderListResponBean bean = (PintuanOrderListResponBean) adapter.getItem(position);
//                new StartActivityUtil(context, PintuanOrderDetailsActivity.class).putExtra(Constants.PINTUANORDER_NO, bean.getId() + "")
//                        .putExtra(Constants.PINTUANORDER_FROM, Constants.PINTUANORDER_FROM_ORDER_LIST)
//                        .startActivity(true);
            }
        });
        recyclerView.setAdapter(adapter);
        LoadingDialogUtils.show(activity);
        currentPage = 1;
        mPresenter.getData(currentPage, mType);
    }

    private void initRefreshLayout() {
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                LoadingDialogUtils.show(activity);
                currentPage++;
                mPresenter.getData(currentPage, mType);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                LoadingDialogUtils.show(activity);
                currentPage = 1;
                refreshLayout.resetNoMoreData();
                mPresenter.getData(currentPage, mType);
            }
        });
    }

    /**
     * 确认收货
     */
//    public void toSureSh(String orderId) {
//        CustomBasePopup customBasePopup = new CustomBasePopup(context, "是否确认收货？", "", "",
//                new CustomBasePopup.PopupWindowCallback() {
//                    @Override
//                    public void sureClickCallback() {
//                        //确认收货
//                        LoadingDialogUtils.show(activity);
//                        mPresenter.ptitakeDelivery(orderId);
//                    }
//
//                    @Override
//                    public void cancelClickCallback() {
//
//                    }
//                });
//        customBasePopup.setPopupGravity(Gravity.CENTER);
//        customBasePopup.showPopupWindow();
//    }
    @Override
    public void initImmersionBar() {
//        super.initImmersionBar();
    }

    @Override
    public void showContent(List<ResaleOrderListResponBean> list) {
        LoadingDialogUtils.dismissDialog_ios();
        if (list == null) {
            list = new ArrayList<>();
        }
        if (currentPage == 1) {
            refreshLayout.finishRefresh();
            adapter.setNewData(list);
        } else {
            if (list.size() < Constants.NUM_OF_PAGE) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore();
            }
            adapter.addData(list);
        }

        if (adapter.getData().size() > 0) {
            stateMain();
        } else {
            stateEmpty();
        }
    }

//    @Override
//    public void showMoreContent(List<PintuanOrderListResponBean> list) {
//
//    }

    @Override
    public void showContentError() {
        LoadingDialogUtils.dismissDialog_ios();
        if (currentPage == 1) {
            refreshLayout.finishRefresh();
        } else {
            currentPage--;
            refreshLayout.finishLoadMore();
        }
        if (adapter == null || adapter.getData().size() == 0) {
            super.stateError();
        }
    }

//    @Override
//    public void refreshContent() {
//        //刷新数据
//        currentPage = 1;
//        refreshLayout.resetNoMoreData();
//        mPresenter.getData(currentPage, mType);
//    }
//
//    @Override
//    public void ptitakeDelivery() {
//        StyleableToast.makeText(context, "收货成功", Toast.LENGTH_SHORT, R.style.mytoast).show();
//        currentPage = 1;
//        refreshLayout.resetNoMoreData();
//        mPresenter.getData(currentPage, mType);
//    }
//
//    ShareShopPopup shareShopPopup;
//
//    @Override
//    public void showPtiptGoodsShare(ShareResponBean shareResponBean) {
//        LoadingDialogUtils.dismissDialog_ios();
//        if (shareResponBean == null || TextUtils.isEmpty(shareResponBean.getShare_image())) {
//            StyleableToast.makeText(context, "获取分享信息失败", Toast.LENGTH_SHORT, R.style.mytoast).show();
//            return;
//        }
//        String shareText = shareResponBean.getShare_text();
//        if (shareShopPopup == null) {
//            shareShopPopup = new ShareShopPopup(context, activity, shareText, new ShareShopPopup.ItemClickCallback() {
//                @Override
//                public void saveImage(String url) {
//                    if (!TextUtils.isEmpty(url)) {
//                        PermissionUtil.requestPermissionForActivity(context, new PermissionUtil.IPermissionListener() {
//                            @Override
//                            public void permissionGranted() {
//                                saveNetImageToLoacl(url);
//                            }
//
//                            @Override
//                            public void permissionDenied() {
//                                ToastUtil.show("权限被拒绝,请设置应用权限");
//                            }
//                        }, "权限被拒绝,请设置应用权限", PermissionUtil.scan_permissions);
//                    }
//                }
//            });
//
//            float fromX = 0;
//            float fromY = 1f;
//            float toX = 0;
//            float toY = 0;
//            Animation showAnimation = createTranslateAnimation(fromX, toX, fromY, toY);
//            Animation dismissAnimation = createTranslateAnimation(toX, fromX, toY, fromY);
//            shareShopPopup.setShowAnimation(showAnimation);
//            shareShopPopup.setDismissAnimation(dismissAnimation);
//            shareShopPopup.setPopupGravity(Gravity.BOTTOM);
//        }
//        shareShopPopup.setImgUrl(shareResponBean.getShare_image());
//        shareShopPopup.showPopupWindow();
//    }

    @Override
    public void stateError() {
    }

    private LoadImageDataThread mLoadDataThread;

    public void saveNetImageToLoacl(String downloadPath) {
        boolean isHttp = PictureMimeType.isHttp(downloadPath);
        LoadingDialogUtils.show(activity, "保存中");
        if (isHttp) {
            mLoadDataThread = new LoadImageDataThread(downloadPath, mHandler, context);
            mLoadDataThread.start();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.SAVE_IMAGE_SUCCESSFUL:
                    try {
                        String path = (String) msg.obj;
                        if (!TextUtils.isEmpty(path)) {
                            if (!SdkVersionUtils.checkedAndroid_Q()) {
                                File file = new File(path);
                                MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), null);
                                new PictureMediaScannerConnection(context, file.getAbsolutePath(), () -> {
                                });
                            }
                            StyleableToast.makeText(context, "图片保存成功", R.style.mytoast).show();
                        }
                        LoadingDialogUtils.dismissDialog_ios();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case Constants.SAVE_IMAGE_ERROR:
                    ToastUtils.s(context, getString(R.string.picture_save_error));
                    LoadingDialogUtils.dismissDialog_ios();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLoadDataThread != null) {
            mHandler.removeCallbacks(mLoadDataThread);
            mLoadDataThread = null;
        }
    }
}
